package io.github.talelin.latticy.controller.v1;


import com.baomidou.mybatisplus.core.metadata.IPage;
import io.github.talelin.core.annotation.*;
import io.github.talelin.latticy.bo.BannerWithItemsBO;
import io.github.talelin.latticy.common.mybatis.Page;
import io.github.talelin.latticy.common.util.PageUtil;
import io.github.talelin.latticy.dto.BannerDTO;
import io.github.talelin.latticy.dto.query.BasePageDTO;
import io.github.talelin.latticy.service.BannerService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.github.talelin.latticy.model.Banner;
import io.github.talelin.latticy.vo.CreatedVO;
import io.github.talelin.latticy.vo.DeletedVO;
import io.github.talelin.latticy.vo.PageResponseVO;
import io.github.talelin.latticy.vo.UpdatedVO;
import javax.validation.constraints.Positive;

/**
* @author tanrentao
* @since 2021-08-10
*/
@Validated
@RestController
@RequestMapping("/v1/banner")
@PermissionModule(value = "Banner")
public class BannerController {

    @Autowired
    private BannerService bannerService;

    @PostMapping("")
    @GroupRequired
    @PermissionMeta(value = "创建Banner")
    public CreatedVO create(@RequestBody @Validated BannerDTO dto) {
        Banner banner = new Banner();
        BeanUtils.copyProperties(dto, banner);
        bannerService.save(banner);
        return new CreatedVO();
    }

    @DeleteMapping("/{id}")
    @GroupRequired
    @PermissionMeta(value = "删除Banner")
    public DeletedVO delete(@PathVariable @Positive(message = "{id.positive}") Integer id) {
        bannerService.delete(id);
        return new DeletedVO();
    }

    @PutMapping("/{id}")
    @GroupRequired
    @PermissionMeta(value = "更新Banner")
    public UpdatedVO update(@RequestBody @Validated BannerDTO dto,
                            @PathVariable @Positive(message = "{id.positive}") Integer id) {
        bannerService.update(dto, id);
        return new UpdatedVO();
    }

    @GetMapping("/{id}")
    @LoginRequired
    @PermissionMeta(value = "查询Banner")
    @Logger(template = "{user.username}查询了Banner数据")
    public BannerWithItemsBO getWithItems(@PathVariable @Positive(message = "{id.positive}") Integer id) {
        return bannerService.getWithItems(id);
    }

    @GetMapping("/page")
    @LoginRequired
    @PermissionMeta(value = "分页查询Banner")
    public PageResponseVO<Banner> getBanners(@Validated BasePageDTO dto) {
        Page<Banner> pager = new Page<>(dto.getPage(), dto.getCount());
        IPage<Banner> paging = bannerService.getBaseMapper().selectPage(pager, null);
        return PageUtil.build(paging);
    }



}
